﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MyLogPC.Config;

namespace MyLogPC
{
    public partial class SettingsFrm : Form
    {
        private string _linkString = string.Empty;
        private string _ipAddress = string.Empty;
        private string _port = string.Empty;
        private AppConfig _config;

        public SettingsFrm()
        {
            InitializeComponent();

            // 加载配置
            _config = ConfigManager.GetConfig();

            // 绑定事件
            btnSave.Click += BtnSave_Click;

            // 初始化UI
            GetSettingsToUI();
        }

        private void GetSettingsToUI()
        {
            try
            {
                // 解析连接参数字符串
                // 格式: "Keyence.KeyenceNanoSerialOverTcp;127.0.0.1;8501_NET"
                // 或: "Melsec.MelsecMcNet;192.168.1.1;6000"
                string connectionParams = _config?.Plc?.ConnectionParameters ?? string.Empty;

                if (!string.IsNullOrEmpty(connectionParams))
                {
                    var parts = connectionParams.Split(';');

                    if (parts.Length >= 3)
                    {
                        // 设置PLC类型
                        string plcType = parts[0];
                        if (plcType.Contains("Keyence"))
                        {
                            comboBox1.SelectedIndex = 1; // Keyence.KeyenceNanoSerialOverTcp;
                        }
                        else if (plcType.Contains("Melsec"))
                        {
                            comboBox1.SelectedIndex = 0; // Melsec.MelsecMcNet;
                        }

                        // 设置IP地址
                        _ipAddress = parts[1];
                        textBox1.Text = _ipAddress;

                        // 设置端口（可能包含其他参数，需要提取数字部分）
                        string portPart = parts[2];
                        string port = ExtractPortFromString(portPart);
                        _port = port;
                        textBox2.Text = _port;

                        // 保存完整的连接字符串
                        _linkString = connectionParams;
                    }
                }
                else
                {
                    // 设置默认值
                    comboBox1.SelectedIndex = 1; // 默认选择Keyence
                    textBox1.Text = "127.0.0.1";
                    textBox2.Text = "8501";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置到UI时发生错误: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SaveSettingsFromUI()
        {
            try
            {
                // 获取UI中的值
                string selectedPlcType = comboBox1.SelectedItem?.ToString() ?? "Keyence.KeyenceNanoSerialOverTcp;";
                _ipAddress = textBox1.Text.Trim();
                _port = textBox2.Text.Trim();

                // 验证输入
                if (string.IsNullOrEmpty(_ipAddress))
                {
                    MessageBox.Show("IP地址不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textBox1.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(_port))
                {
                    MessageBox.Show("端口不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textBox2.Focus();
                    return;
                }

                // 验证端口是否为数字
                if (!int.TryParse(_port, out int portNumber) || portNumber <= 0 || portNumber > 65535)
                {
                    MessageBox.Show("端口必须是1-65535之间的数字", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textBox2.Focus();
                    return;
                }

                // 验证IP地址格式
                if (!IsValidIPAddress(_ipAddress))
                {
                    MessageBox.Show("IP地址格式不正确", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textBox1.Focus();
                    return;
                }

                // 构建连接字符串
                string connectionString;
                if (selectedPlcType.Contains("Keyence"))
                {
                    connectionString = $"Keyence.KeyenceNanoSerialOverTcp;{_ipAddress};{_port}_NET";
                }
                else
                {
                    connectionString = $"Melsec.MelsecMcNet;{_ipAddress};{_port}";
                }

                // 更新配置
                _config.Plc.ConnectionParameters = connectionString;
                _linkString = connectionString;

                // 保存配置到文件
                ConfigManager.SaveConfig(_config);

                MessageBox.Show("配置保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置时发生错误: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 从字符串中提取端口号
        /// </summary>
        /// <param name="portString">端口字符串，如"8501_NET"</param>
        /// <returns>端口号</returns>
        private string ExtractPortFromString(string portString)
        {
            if (string.IsNullOrEmpty(portString))
                return "8501";

            // 提取数字部分
            var digits = new StringBuilder();
            foreach (char c in portString)
            {
                if (char.IsDigit(c))
                    digits.Append(c);
                else
                    break; // 遇到非数字字符停止
            }

            return digits.Length > 0 ? digits.ToString() : "8501";
        }

        /// <summary>
        /// 验证IP地址格式
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <returns>是否有效</returns>
        private bool IsValidIPAddress(string ipAddress)
        {
            return System.Net.IPAddress.TryParse(ipAddress, out _);
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private void BtnSave_Click(object? sender, EventArgs e)
        {
            SaveSettingsFromUI();
            //重启应用程序
            Application.Restart();
        }
    }
}
